/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import cn.hutool.core.collection.CollUtil;
import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.service.pms.response.PmsProductSkuDto;
import com.lxk.service.pms.response.PmsProductSpuDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.json.utils.JsonUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 计算原始订单金额
 *
 * @author heyi
 * 2024/8/21
 */
@LiteflowComponent(value = FlowOrderNodeConst.ORIGINAL_AMOUNT_ORDER)
@AllArgsConstructor
public class OrderOriginalAmountNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);
    @Override
    public void beforeProcess() {
        OrderContext context = this.getContextBean(OrderContext.class);
        List<OrderContext.SkuInfo> skuInfoList = context.getSkuInfoList();
        if (CollUtil.isEmpty(skuInfoList)) {
            log.error("OrderOriginalAmountNode:{}", context);
            throw new ServiceException("商品信息为空");
        }
    }

    @Override
    public void process() throws Exception {
        OrderContext context = this.getContextBean(OrderContext.class);
        Long merId = context.getMerId();
        Long userId = context.getUserId();
        List<OrderContext.SkuInfo> skuInfoList = context.getSkuInfoList();
        skuInfoList.forEach(item -> {
            Integer count = item.getCount();
            PmsProductSpuDto spu = item.getSpu();
            List<PmsProductSkuDto> pmsProductSkuDtoList = item.getPmsProductSkuDtoList();
            PmsProductSkuDto pmsProductSkuDto = pmsProductSkuDtoList.get(0);
            String picUrl = pmsProductSkuDto.getPicUrl();
            Long skuId = pmsProductSkuDto.getId();
            Long spuId = pmsProductSkuDto.getSpuId();
            String skuName = pmsProductSkuDto.convertSkuName(p -> JsonUtils.parseArray(p, PmsProductSkuDto.Properties.class));
            // 订单单价
            BigDecimal orderPrice = pmsProductSkuDtoList.stream().map(PmsProductSkuDto::getPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            // 订单总价
            BigDecimal totalOrderPrice = orderPrice.multiply(new BigDecimal(count));
            // 订单成本
            BigDecimal orderCostPrice = pmsProductSkuDtoList.stream().map(PmsProductSkuDto::getCostPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            // 订单成本总价
            BigDecimal totalOrderCostPrice = orderCostPrice.multiply(new BigDecimal(count));
            BigDecimal orderMarkerPrice = pmsProductSkuDtoList.stream().map(PmsProductSkuDto::getMarketPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            // 订单市场总价
            BigDecimal totalOrderMarkerPrice = orderMarkerPrice.multiply(new BigDecimal(count));
            // 订单利润
            BigDecimal orderProfitPrice = orderPrice.subtract(orderCostPrice);
            BigDecimal totalOrderProfitPrice = totalOrderPrice.subtract(totalOrderCostPrice);
            context.addActPayPrice(totalOrderPrice);
            context.addTotalPrice(totalOrderPrice);
            context.addPayPrice(totalOrderPrice);
            context.addOrderCostPrice(totalOrderCostPrice);
            context.addOrderMarkerPrice(totalOrderMarkerPrice);
            context.addOrderProfitPrice(totalOrderProfitPrice);
            // 设置订单详细
            OmsOrderItemBo orderItemBo = new OmsOrderItemBo();
            orderItemBo.setPrice(orderPrice);
            orderItemBo.setSkuName(skuName);
            orderItemBo.setSkuId(skuId);
            orderItemBo.setSpuId(spuId);
            orderItemBo.setMerId(merId);
            orderItemBo.setUserId(userId);
            orderItemBo.setOrderType(context.getOrderType().getCode());
            orderItemBo.setPicUrl(picUrl);
            orderItemBo.setCount(count);
            orderItemBo.setSaleAfterNum(count);
            orderItemBo.setSaleAfterNumSold(0);
            orderItemBo.setSaleAfterStatus(OrderEnums.SaleAfterStatus.NOT.getCode());
            orderItemBo.setTotalPrice(totalOrderPrice);
            orderItemBo.setOrderProfitPrice(orderProfitPrice);
            orderItemBo.setTotalOrderProfitPrice(totalOrderProfitPrice);
            orderItemBo.setOrderCostPrice(orderCostPrice);
            orderItemBo.setTotalOrderCostPrice(totalOrderCostPrice);
            orderItemBo.setOrderMarkerPrice(orderMarkerPrice);
            orderItemBo.setTotalOrderMarkerPrice(totalOrderMarkerPrice);
            orderItemBo.setDiscountPrice(BigDecimal.ZERO);
            orderItemBo.setTwoCategoryId(spu.getCategoryId());
            orderItemBo.setSpuName(spu.getName());
            context.addOrderItem(orderItemBo);
        });
    }

    @Override
    public boolean isAccess() {
        OrderContext context = this.getContextBean(OrderContext.class);
        return context.getNeedStock();
    }
}
